package source.backtrace;

import java.util.ArrayList;
import java.util.List;

public class CombinationSum {
    List<List<Integer>> ans = new ArrayList<>();
    List<Integer> combine = new ArrayList<>();

    public List<List<Integer>> combinationSum(int[] candidates, int target) {

        dfs(candidates, target, 0);
        return ans;
    }

    void dfs(int[] candidates, int target, int index) {
        if (index == candidates.length)
            return;

        if (target == 0) {
            ans.add(new ArrayList<>(combine));
            return;
        }

        dfs(candidates, target, index + 1);

        if (target - candidates[index] >= 0) {
            combine.add(candidates[index]);
            dfs(candidates, target - candidates[index], index);
            combine.remove(combine.size() - 1);
        }

    }

    /**
     * 数字 n 代表生成括号的对数，请你设计一个函数，用于能够生成所有可能的并且 有效的 括号组合。
     */
    public List<String> generateParenthesis(int n) {
        List<String> list = new ArrayList<>();
        backtrace(list,new StringBuilder(), 0, 0, n);

        return list;
    }

    private void backtrace(List<String> list,StringBuilder s, int open, int close, int n) {
        if(s.length() == 2*n){
            list.add(s.toString());
            return;
        }
        if (open < n){
            s.append('(');
            backtrace(list,s, open+1, close, n);
            s.deleteCharAt(s.length()-1);
        }
        if (close < open){
            s.append(')');
            backtrace(list,s, open, close+1, n);
            s.deleteCharAt(s.length()-1);
        }
    }
}
